using AdminApi.Dto;
using AdminApi.Domain;
using AdminApi.Repositories;
using Microsoft.AspNetCore.Mvc;

namespace AdminApi.Controllers;

[ApiController]
[Route("api/blogs/{blogId}/comments")]
public class BlogsCommentsController : ControllerBase
{
    private readonly IRepository<Comments> _repComments;
    private readonly IRepository<Blogs> _repBlogs;
    public BlogsCommentsController(IRepository<Comments> repComments,IRepository<Blogs> repBlogs)
    {
        _repComments = repComments;
        _repBlogs = repBlogs;
    }

    [HttpGet]
    public async Task<IActionResult> Get(Guid blogId)
    {
        var comments = (await _repComments.GetAllAsync()).Where(x=>x.BlogId == blogId).ToList();
        if(comments == null || comments.Count == 0)
        {
            return Ok(ApiResultDto<List<Comments>>.Fail(1004,"没有找到对应评论"));
        }
        return Ok(ApiResultDto<List<Comments>>.Success(comments,"查询列表成功"));
    }

    [HttpPost]
    public async Task<IActionResult> Post(Guid blogId,BlogCommentCreateDto commentCreateDto)
    {
        var blog = await _repBlogs.GetByIdAsync(blogId);
        if(blog == null)
        {
            return Ok(ApiResultDto<object>.Fail(1004,"没有此博客"));
        }
        if(blog.IsDeleted)
        {
            return Ok(ApiResultDto<object>.Fail(1004,"此博客已被删除，请确认后重试"));
        }
        if(!blog.IsActived)
        {
            return Ok(ApiResultDto<object>.Fail(1004,"此博客未生效，请确认后重试"));
        }
        var comment = await _repComments.CreateAsync(new Comments{BlogId = blogId,Contents=commentCreateDto.Content});
        return Ok(ApiResultDto<Comments>.Success(comment));
    }
}